import argparse
import logging
import asyncio
import yaml

from kademlia.network import Server
from kademlia.storage import PHashStorage

import faulthandler

faulthandler.enable()

handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
log = logging.getLogger("kademlia")
log.addHandler(handler)
log.setLevel(logging.DEBUG)

config = yaml.load(
    open("/mnt/e/pydev/drpchain/config.yaml").read(), Loader=yaml.FullLoader
)
print(config)


def parse_arguments():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-n",
        "--no",
        help="no in config",
        type=int,
        default=None,
    )

    parser.add_argument(
        "-u",
        "--upload",
        help="whether upload image",
        type=bool,
        default=False,
    )
    return parser.parse_args()


def create_bootstrap_node(no):
    loop = asyncio.get_event_loop()
    # loop.set_debug(True)

    server = Server()
    server.node.ip = "127.0.0.1"
    node_info = config["nodes"]["list"][no].split(",")
    server.node.port = int(node_info[0])
    loop.run_until_complete(server.listen(server.node.port))

    if eval(node_info[1]):
        server.data_send_start(no * 1000, (no + 1) * 1000)
        
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.stop()
        loop.close()


def connect_to_bootstrap_node(args):
    loop = asyncio.get_event_loop()
    # loop.set_debug(True)

    server = Server()
    no = args[2] - args[0]
    node_info = config["nodes"]["list"][no].split(",")

    server.node.ip = "127.0.0.1"
    node_info = config["nodes"]["list"][no].split(",")
    server.node.port = int(node_info[0])
    loop.run_until_complete(server.listen(server.node.port))
    bootstrap_node = tuple(config["nodes"]["bootstrap"])
    print(bootstrap_node)
    loop.run_until_complete(server.bootstrap([bootstrap_node]))

    if eval(node_info[1]):
        server.data_send_start(no * 1000, (no + 1) * 1000)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.stop()
        loop.close()

